import axios from 'axios'
import { Message } from 'element-ui'
import { getToken, getTenantId } from "@/utils/ProjectTools";
import store from '@/store'
import router from "@/router";

// create an axios instance
const service = axios.create({
    baseURL: '/admin-api',
    timeout: 10 * 60 * 1000
})

// request interceptor
service.interceptors.request.use(
    config => {
        const token = getToken()
        if (token) {
            config.headers['Authorization'] =  'Bearer ' + token
        }
        const tenantId = getTenantId()
        console.log('tenantId',tenantId)
        if (tenantId) {
            config.headers['Tenant-Id'] = tenantId
        }
        return config
    },
    error => {
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        console.log(res)
        if (res.code === 0) {
            return res
        }
        Message({
            message: res.msg || 'Error',
            type: 'error',
            duration: 5 * 1000
        })

        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 401) {
            store.commit('user/LOGOUT')
            router.replace({
                path: '/login',
            })
        }
        return Promise.reject(new Error(res.message || 'Error'))
    },
    error => {
        console.log('err' + error.msg) // for debug
        Message({
            message: error.msg,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
